//
//  ClubGameDetailView.swift
//  77Club
//
//  Created by Apple on 2024/9/3.
//

import UIKit
import Cosmos
import VersaPlayer

class ClubGameDetailTopView: UIView, RaeNetworkProtocol {

    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(12.0.Scale).mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .font(16.font_semiBold).color(.white).end()
    private let subLabel = c_make_ex(UILabel.self)
        .font(12.font_medium).color(.white.alpha(0.7)).end()
    private let bottomLabel = UIIconButton(style: .trailing(itemSpace: 0))
    private let attentionButton = c_make_ex(UIButton.self)
        .image("GameDetail_follow").image("GameDetail_followed", state: .selected).end()
    private var starView = ClubGameDetailScoreView()
    private let backView_one = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.2)).corner(12.0.Scale).end()
    private let backView_two = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.2)).corner(12.0.Scale).end()
    private let backView_three = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.2)).corner(12.0.Scale).end()
    private let backView_four = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.2)).corner(12.0.Scale).end()
    private let recommendImg = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Home_detail_recommend").end()
    private let title_two = c_make_ex(UILabel.self)
        .font(14.font_semiBold).color(.white).alignment(.center).end()
    private let sub_two = c_make_ex(UILabel.self)
        .font(12.font_medium).text("游戏大小")
        .color(.white.alpha(0.5)).alignment(.center).end()
    private let title_three = c_make_ex(UILabel.self)
        .font(14.font_semiBold).color(.white).alignment(.center).end()
    private let sub_three = c_make_ex(UILabel.self)
        .font(12.font_medium).text("乐玩榜")
        .color(.white.alpha(0.5)).alignment(.center).end()
    private let title_four = c_make_ex(UILabel.self)
        .font(14.font_semiBold).color(.white).alignment(.center).end()
    private let sub_four = c_make_ex(UILabel.self)
        .font(12.font_medium).text("关注数")
        .color(.white.alpha(0.5)).alignment(.center).end()
    
    var topModel: ClubGameDetailModel? {
        didSet{
            guard let md = topModel else { return }
            iconImageView.loadImage(url: md.icon)
            nameLabel.text = md.name
            let tagStr = md.biaoqian.joined(separator: " · ")
            subLabel.text = tagStr
            title_two.text = "\(md.size)"
            title_three.text = md.orderby
            title_four.text = md.follow
            starView.scoreLabel.text = String(md.point)
            attentionButton.isSelected = md.shoucang == 1
        }
    }
    
    var detailModel: ClubGameDetailInfoModel?{
        didSet{
            starView.model = detailModel
            self.bottomLabel.isHidden = true
            guard let md = detailModel else { return }
            if let result = md.pzyq.components(separatedBy: "\r").first, result.count > 0 {
                self.bottomLabel.isHidden = false
                self.bottomLabel.setTitle(result, for: .normal)
            }
        }
    }
    var gameId: String = ""
    
    var toInfoDetailBlock: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .clear

        subviews{
            iconImageView
            nameLabel
            subLabel
            bottomLabel
            attentionButton
            starView
            backView_one.subviews{
                recommendImg
            }
            backView_two.subviews{
                title_two
                sub_two
            }
            backView_three.subviews{
                title_three
                sub_three
            }
            backView_four.subviews{
                title_four
                sub_four
            }
        }
        
        let width = (CGFloat.screenWidth-60.0.Scale)/4
        iconImageView.leading(12.0.Scale).top(8.0.Scale).size(80.0.Scale)
        nameLabel.leading(100.0.Scale).top(20.0.Scale).trailing(91.0.Scale)
        subLabel.leading(100.0.Scale).top(43.0.Scale).trailing(91.0.Scale)
        bottomLabel.leading(100.0.Scale).trailing(91.0.Scale).height(16.0.Scale)
        bottomLabel.Top == subLabel.Bottom + 1.0.Scale
        attentionButton.trailing(12.0.Scale).top(35.0.Scale).width(66.0.Scale).height(26.0.Scale)
        starView.leading(0).trailing(0).height(93.0.Scale)
        starView.Top == iconImageView.Bottom + 16.0.Scale
        backView_one.leading(12.0.Scale).height(60.0.Scale).width(width).bottom(8.0.Scale)
        backView_one.Top == starView.Bottom + 16.0.Scale
        recommendImg.height(32.0.Scale).width(65.0.Scale).centerVertically().centerHorizontally()
        backView_two.height(60.0.Scale).width(width)
        backView_two.CenterY == backView_one.CenterY
        backView_two.Leading == backView_one.Trailing + 12.0.Scale
        title_two.leading(5).trailing(5).top(12.0.Scale)
        sub_two.leading(5).trailing(5).bottom(12.0.Scale)
        backView_three.height(60.0.Scale).width(width)
        backView_three.CenterY == backView_two.CenterY
        backView_three.Leading == backView_two.Trailing + 12.0.Scale
        title_three.leading(5).trailing(5).top(12.0.Scale)
        sub_three.leading(5).trailing(5).bottom(12.0.Scale)
        backView_four.height(60.0.Scale).width(width)
        backView_four.CenterY == backView_two.CenterY
        backView_four.Leading == backView_three.Trailing + 12.0.Scale
        title_four.leading(5).trailing(5).top(12.0.Scale)
        sub_four.leading(5).trailing(5).bottom(12.0.Scale)
        
        bottomLabel.style { v in
            v.iconSize = CGSize(width: 16.0.Scale, height: 16.0.Scale)
            v.setImage("Home_game_right".toImage, for: .normal)
            v.setTitleColor(.white.alpha(0.6), for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.contentHorizontalAlignment = .left
            v.addTarget(self, action: #selector(clickBottomLabel), for: .touchUpInside)
            v.isHidden = true
        }
        
        attentionButton.addTarget(self, action: #selector(clickAttentionButton), for: .touchUpInside)
    }
    
    @objc private func clickAttentionButton(){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            ToastUtil.show()
            if attentionButton.isSelected {
                Task{
                    let res = await network.request(.cancelCollectGoods(goodsId: topModel?.shoucang_id ?? "", type: "0"),isShowError: false)
                    if res.isSuccess {
                        "已取消关注".toast_success
                        title_four.text = ClubGlobalTool.shared.subtractionNumberInString(text: title_four.text ?? "")
                        attentionButton.isSelected = false
                    }
                }
            }else{
                Task{
                    let res = await network.request(.collectGoods(goodsId: gameId, type: "0"),isShowError: false)
                    if res.isSuccess {
                        "关注成功".toast_success
                        title_four.text = ClubGlobalTool.shared.calculateNumberInString(text: title_four.text ?? "")
                        attentionButton.isSelected = true
                    }
                }
            }
            
        }else{
            UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    @objc private func clickBottomLabel(){
        toInfoDetailBlock?()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: =================HeaderView=================
class ClubGameDetailHeaderView: UITableViewHeaderFooterView {
         
    private let titleLabel = c_make_ex(UILabel.self)
        .font(14.font_semiBold).color(.white).end()
    var allButton = UIIconButton(style: .trailing(itemSpace: 0))
    
    var titleStr: String = "" {
        didSet{
            titleLabel.text = titleStr
            allButton.isHidden = !(titleStr == "游戏简介")
        }
    }
    
    var didAllButton:(()->())?
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        backgroundView = UIView()
        backgroundView?.backgroundColor = .clear
        
        subviews{
            titleLabel
            allButton
        }

        titleLabel.leading(12.0.Scale).top(8.0.Scale)
        allButton.trailing(12.0.Scale).height(14.0.Scale)
        allButton.CenterY == titleLabel.CenterY
        
        allButton.style { v in
            v.iconSize = CGSize(width: 14.0.Scale, height: 14.0.Scale)
            v.setImage("Home_game_right".toImage, for: .normal)
            v.setTitleColor(.white.alpha(0.6), for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.setTitle("全部", for: .normal)
            v.contentHorizontalAlignment = .right
            v.addTarget(self, action: #selector(clickAllButton), for: .touchUpInside)
            v.isHidden = true
        }
    }
    
    @objc private func clickAllButton(){
        didAllButton?()
    }

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}

//MARK: =================玩家评论HeaderView=================
class ClubGameDetailCommitHeaderView: UITableViewHeaderFooterView {
       
    private let bgView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12.0.Scale, corners: [.layerMinXMinYCorner,.layerMaxXMinYCorner]).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .font(14.font_semiBold).color("#323233").text("玩家评论").end()
    private let sortButton = c_make_ex(UIButton.self)
        .image("GameDetail_sortNor").image("GameDetail_sortSel", state: .selected).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(16.0.Scale).mode(.scaleAspectFill).end()
    private let commitLabel = c_make_ex(UILabel.self)
        .font(16.font_semiBold).color("#FF7700")
        .text("轻触发布你的评价").end()
    private var starView = CosmosView()
    private let starButton = c_make_ex(UIButton.self).end()
    
    var updateDataBlock: ((_: String) -> Void)?
    var commitBlock: (() -> Void)?
    
    var sortBy: String = "0"{
        didSet{
            self.sortButton.isSelected = sortBy == "0"
        }
    }
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        backgroundView = UIView()
        backgroundView?.backgroundColor = .clear
        
        subviews{
            bgView.subviews{
                titleLabel
                sortButton
                iconImageView
                commitLabel
                starView
                starButton
            }
        }
        
        bgView.top(0).trailing(0).width(.screenWidth).height(100.0.Scale)
        titleLabel.leading(12.0.Scale).top(14.0.Scale)
        sortButton.top(8.0.Scale).trailing(12.0.Scale).width(76.0.Scale).height(28.0.Scale)
        iconImageView.leading(12.0.Scale).top(52.0.Scale).size(32.0.Scale)
        commitLabel.leading(52.0.Scale)
        commitLabel.CenterY == iconImageView.CenterY
        starView.trailing(12.0.Scale).width(142.0.Scale).height(22.0.Scale)
        starView.CenterY == iconImageView.CenterY
        starButton.trailing(12.0.Scale).width(142.0.Scale).height(22.0.Scale)
        starButton.CenterY == iconImageView.CenterY
        
        sortButton.addTarget(self, action: #selector(clickSortButton), for: .touchUpInside)
        
        starView.rating = 0
        starView.settings.starSize = 22.0.Scale
        starView.settings.starMargin = 8.0.Scale
        starView.settings.emptyImage = "GameDetail_commitStar".toImage
        starView.isUserInteractionEnabled = false
        
        starButton.addTarget(self, action: #selector(toCommiteVC), for: .touchUpInside)
        
        if ClubUser.face.count > 0 {
            iconImageView.loadImage(url: ClubUser.face)
        }else{
            iconImageView.image = "Common_defaultIcon".toImage
        }
    }
    
    @objc private func toCommiteVC(){
        commitBlock?()
    }
    
    @objc private func clickSortButton(){
        
        sortButton.isSelected = !sortButton.isSelected
        let sortType = sortButton.isSelected ? "0" : "1"
        updateDataBlock?(sortType)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}


//MARK: =================GamePicCell=================
class ClubGameDetailGamePicCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let cateView = ClubGameDetailPicCateView()
    
    private var cateType = "1"
    private var imgs_set = "1"
    private var avatar_set = "1"
    private var play_set = "1"
    private var imgs = [ClubGameDetailMediaItemModel]()
    private var avatar = [ClubGameDetailMediaItemModel]()
    private var play = [ClubGameDetailMediaItemModel]()
    private var isOnlyVideo = false //是否只有一个视频
    // 记录上次可见的 Cell IndexPaths
    private var previousVisibleIndexPaths: Set<IndexPath> = []
    /// 点击图片
    var didSelectImage:((_:Int,_:[String])->())?
    /// 点击视频
    var didSelectVideo:((_:String)->())?
    var updateTableviewUI:((_:String)->())?
    var isLeft = false
    
    var imageModel: ClubGameDetailInfoModel? {
        didSet{
            guard let picture = imageModel?.picture else { return }
            var cateArr = [String]()
            if picture.avatar.count > 0 {
                avatar = picture.avatar
                cateArr.append("1")
            }
            if picture.play.count > 0 {
                play = picture.play
                cateArr.append("2")
            }
            if picture.imgs.count > 0 {
                imgs = picture.imgs
                cateArr.append("3")
            }
            if picture.cateType == "0" {
                if cateArr.count > 0 {
                    cateType = cateArr[0]
                }
            }else{
                cateType = picture.cateType
            }
            
            imgs_set = picture.imgs_set
            avatar_set = picture.avatar_set
            play_set = picture.play_set
            cateView.cateArray = cateArr
            cateView.cateStr = cateType

            if cateType == "1" {
                cateView.numStr = "1/\(avatar.count)"
            }else if cateType == "2"{
                cateView.numStr = "1/\(play.count)"
            }else if cateType == "3"{
                cateView.numStr = "1/\(imgs.count)"
            }
            updateCollectionView()
        }
    }
    
    private func updateCollectionView(){
        if cateType == "1" {
            if avatar_set == "1"{
                if avatar.count == 1 && avatar[0].type != "img" {
                    self.isOnlyVideo = true
                    let w = CGFloat.screenWidth - 24.0.Scale
                    collectionView.heightConstraint?.constant = w
                }else{
                    self.isOnlyVideo = false
                    collectionView.heightConstraint?.constant = 351.0.Scale
                }
            }else{
                collectionView.heightConstraint?.constant = 197.0.Scale
            }
        }else if cateType == "2" {
            if play_set == "1"{
                if play.count == 1 && play[0].type != "img" {
                    self.isOnlyVideo = true
                    let w = CGFloat.screenWidth - 24.0.Scale
                    collectionView.heightConstraint?.constant = w
                }else{
                    self.isOnlyVideo = false
                    collectionView.heightConstraint?.constant = 351.0.Scale
                }
            }else{
                collectionView.heightConstraint?.constant = 197.0.Scale
            }
        }else if cateType == "3" {
            if imgs_set == "1"{
                if imgs.count == 1 && imgs[0].type != "img" {
                    self.isOnlyVideo = true
                    let w = CGFloat.screenWidth - 24.0.Scale
                    collectionView.heightConstraint?.constant = w
                }else{
                    self.isOnlyVideo = false
                    collectionView.heightConstraint?.constant = 351.0.Scale
                }
            }else{
                collectionView.heightConstraint?.constant = 197.0.Scale
            }
        }
        collectionView.reloadData()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            if !self.isLeft {
                if let cell = self.collectionView.cellForItem(at: IndexPath(row: 0, section: 0)) {
                    self.playVideo(in: cell)
                }
            }
        }        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        subviews{
            collectionView
            cateView
        }
        let layout = ClubDetailGamePicFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
//        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 12.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubGameDetailGamePicItemCell.self, forCellWithReuseIdentifier: ClubGameDetailGamePicItemCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
//        collectionView.isPagingEnabled = true

        collectionView.leading(12.0.Scale).trailing(12.0.Scale).height(197.0.Scale).top(8.0.Scale).bottom(8.0.Scale)
        cateView.leading(50).trailing(0).height(30.0.Scale)
        cateView.Bottom == collectionView.Bottom

        cateView.updateCateData = { type in
            self.cateType = type
            self.updateTableviewUI?(type)
            if type != "1" {
                self.stopVideoPlay()
            }
            let indexPath = IndexPath(item: 0, section: 0)
            self.collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(stopAudioPlay), name: .stopAudioPlayer, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(inPlayVC), name: .inPlayAudioVC, object: nil)
    }
    
    private func stopVideoPlay(){
        
        for section in 0..<collectionView.numberOfSections {
            for item in 0..<collectionView.numberOfItems(inSection: section) {
                let indexPath = IndexPath(item: item, section: section)
                if let cell = collectionView.cellForItem(at: indexPath) as? ClubGameDetailGamePicItemCell {
                    cell.stopAudioPlay()
                }
            }
        }

    }
    
    @objc private func stopAudioPlay(){
        self.isLeft = true
    }
    
    @objc private func inPlayVC(){
        self.isLeft = false
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if cateType == "1" {
            return avatar.count
        }else if cateType == "2" {
            return play.count
        }else {
            return imgs.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubGameDetailGamePicItemCell.description(), for: indexPath) as? ClubGameDetailGamePicItemCell else { return UICollectionViewCell() }
        if cateType == "1" {
            cell.model = avatar[indexPath.row]
            cell.setType = avatar_set
        }else if cateType == "2" {
            cell.model = play[indexPath.row]
            cell.setType = play_set
        }else {
            cell.model = imgs[indexPath.row]
            cell.setType = imgs_set
        }
        cell.onlyVideo = isOnlyVideo
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        var imgArray = [String]()
        if cateType == "1" {
            let md = avatar[indexPath.row]
            if md.type != "img" {
                return
            }else{
                for md in avatar{
                    if md.type == "img"{
                        imgArray.append(md.path)
                    }
                }
            }
        }else if cateType == "2"{
            let md = play[indexPath.row]
            if md.type != "img" {
                return
            }else{
                for md in play{
                    if md.type == "img"{
                        imgArray.append(md.path)
                    }
                }
            }
        }else if cateType == "3"{
            let md = imgs[indexPath.row]
            if md.type != "img" {
                return
            }else{
                for md in imgs{
                    if md.type == "img"{
                        imgArray.append(md.path)
                    }
                }
            }
        }
        didSelectImage?(indexPath.row,imgArray)
    }
    
    // 当 cell 即将显示时调用
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        // 对即将显示的 cell 进行操作，例如开始视频播放
        if let customCell = cell as? ClubGameDetailGamePicItemCell {
            if cateType == "1" {
                let md = avatar[indexPath.row]
                if md.type == "img"{
                    customCell.stopPlay()
                }else{
                    if !isLeft {
                        customCell.playVideo()
                    }
                }
            }else if cateType == "2"{
                let md = play[indexPath.row]
                if md.type == "img"{
                    customCell.stopPlay()
                }else{
                    if !isLeft {
                        customCell.playVideo()
                    }
                }
            }else if cateType == "3"{
                let md = imgs[indexPath.row]
                if md.type == "img"{
                    customCell.stopPlay()
                }else{
                    if !isLeft {
                        customCell.playVideo()
                    }
                }
            }
        }
    }
    // 当 cell 离开屏幕时调用
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        // 对已经滑出屏幕的 cell 进行操作，例如停止视频播放
        if let customCell = cell as? ClubGameDetailGamePicItemCell {
            customCell.stopPlay()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        var sizeType = 2
        if cateType == "1" {
            if avatar_set == "1"{
                sizeType = 1
            }
        }else if cateType == "2" {
            if play_set == "1"{
                sizeType = 1
            }
        }else if cateType == "3" {
            if imgs_set == "1"{
                sizeType = 1
            }
        }
        if sizeType == 1 {
            if isOnlyVideo{
                let w = CGFloat.screenWidth - 24.0.Scale
                return CGSize(width: w, height: w)
            }else{
                return CGSize(width: 209.0.Scale, height: 351.0.Scale)
            }
        }else {
            return CGSize(width: CGFloat.screenWidth - 24.0.Scale, height: 197.0.Scale)
        }
     }


     func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
         
         let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.bounds.size)
         let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
         if let indexPath = collectionView.indexPathForItem(at: visiblePoint) {
             var count = 0
             if cateType == "1" {
                 count = avatar.count
             }else if cateType == "2"{
                 count = play.count
             }else if cateType == "3"{
                 count = imgs.count
             }
             if let cell = collectionView.cellForItem(at: indexPath) {
                 playVideo(in: cell)
             }
             cateView.numStr = "\(indexPath.row + 1)/\(count)"
         }
     }

    // 播放视频逻辑
    func playVideo(in cell: UICollectionViewCell) {
        // 停止其他 Cell 的播放
        stopAllVideos()
        
        // 播放当前 Cell 的视频
        if let videoCell = cell as? ClubGameDetailGamePicItemCell {
            videoCell.playVideo()
        }
    }

    // 停止所有视频逻辑
    func stopAllVideos() {
        let visibleCells = collectionView.visibleCells
        for cell in visibleCells {
            if let videoCell = cell as? ClubGameDetailGamePicItemCell {
                videoCell.stopPlay()
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class ClubDetailGamePicFlowLayout: UICollectionViewFlowLayout {
    
    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        guard let collectionView = self.collectionView else { return proposedContentOffset }

        let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.width, height: collectionView.bounds.height)
        guard let layoutAttributes = super.layoutAttributesForElements(in: targetRect) else { return proposedContentOffset }

        let centerX = proposedContentOffset.x + collectionView.bounds.width / 2
        var closestAttribute: UICollectionViewLayoutAttributes?

        for attributes in layoutAttributes {
            if closestAttribute == nil || abs(attributes.center.x - centerX) < abs(closestAttribute!.center.x - centerX) {
                closestAttribute = attributes
            }
        }

        guard let closest = closestAttribute else { return proposedContentOffset }

        let offsetX = closest.center.x - collectionView.bounds.width / 2
        return CGPoint(x: max(0, offsetX), y: proposedContentOffset.y)
    }
}



class ClubGameDetailGamePicItemCell: UICollectionViewCell {
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(12.0.Scale).end()
    let playerView = VersaPlayerView()
    private var controls = VersaPlayerControls()
    private let volunmButton = c_make_ex(UIButton.self)
        .image("Dynamic_video_aloud").image("Dynamic_video_slience", state: .selected).end()
    var isLeft = false {
        didSet{
            if isLeft {
                self.stopPlay()
            }
        }
    }
    
    var model: ClubGameDetailMediaItemModel? {
        didSet{
            guard let md = model else { return }
            if md.type == "img"{
                playerView.isHidden = true
                iconImageView.isHidden = false
                volunmButton.isHidden = true
                iconImageView.loadImage(url: md.path)
            }else{
                playerView.isHidden = false
                iconImageView.isHidden = true
                volunmButton.isHidden = false
                if let url = URL.init(string: md.path) {
                    let item = VersaPlayerItem(url: url)
                    playerView.set(item: item)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        self.playerView.pause()
                    }
                }
            }
        }
    }
    
    var setType: String = "" {
        didSet{
            if self.setType == "1" {
                self.playerView.widthConstraint?.constant = 197.0.Scale
                self.iconImageView.widthConstraint?.constant = 197.0.Scale
                playerView.renderingView.playerLayer.videoGravity = .resizeAspect
            }else{
                self.playerView.widthConstraint?.constant = CGFloat.screenWidth - 24.0.Scale
                self.iconImageView.widthConstraint?.constant = CGFloat.screenWidth - 24.0.Scale
                playerView.renderingView.playerLayer.videoGravity = .resizeAspectFill
            }
        }
    }
    
    var onlyVideo: Bool = false {
        didSet{
            if onlyVideo {
                self.playerView.widthConstraint?.constant = CGFloat.screenWidth - 24.0.Scale
            }
        }
    }
    
    func stopPlay(){
        playerView.player.volume = 0
        playerView.pause()
    }
    
    func playVideo(){
        playerView.player.volume = 1
        playerView.play()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            iconImageView
            playerView
            volunmButton
        }
              
        
        iconImageView.leading(0).top(0).bottom(0).width(200)
        playerView.leading(0).top(0).bottom(0).width(200)
        volunmButton.leading(12).bottom(12).size(14)
        
        playerView.use(controls: controls)
        playerView.isUserInteractionEnabled = false
        playerView.layer.cornerRadius = 12.0.Scale
        playerView.layer.masksToBounds = true
        playerView.backgroundColor = .black

        volunmButton.addTarget(self, action: #selector(clickVolunmButton), for: .touchUpInside)
        NotificationCenter.default.addObserver(self, selector: #selector(stopAudioPlay), name: .stopAudioPlayer, object: nil)
    }
    
    @objc func stopAudioPlay(){
        playerView.pause()
        playerView.player.replaceCurrentItem(with: nil)
    }
    
    @objc private func clickVolunmButton(){
        
        volunmButton.isSelected = !volunmButton.isSelected
        playerView.player.volume = volunmButton.isSelected ? 0 : 1
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: =================
class ClubGameDetailGameInfoCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource {

    private let contentLabel = c_make_ex(UILabel.self)
        .color(.white).line(3).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .black.alpha(0.2)
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubGameDetailActiveCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 36.0.Scale
        tableView.layer.cornerRadius = 12.0.Scale
        tableView.layer.masksToBounds = true
        return tableView
    }()
    
    var model: ClubGameDetailInfoModel? {
        didSet{
            guard let md = model else { return }
            if let data = md.content.data(using: .utf8) {
                // 将 HTML 转换为 NSAttributedString
                let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
                    .documentType: NSAttributedString.DocumentType.html,
                    .characterEncoding: String.Encoding.utf8.rawValue
                ]
                if let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) {
                    // 将 NSAttributedString 转换为 NSMutableAttributedString
                    let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)
                    //
                    let fullRange = NSRange(location: 0, length: mutableAttributedString.length)
                    // 设置段落样式
                    let paragraphStyle = NSMutableParagraphStyle()
                    paragraphStyle.lineBreakMode = .byTruncatingTail // 设置省略号
                    paragraphStyle.alignment = .left
                    paragraphStyle.lineSpacing = 5  // 设置行间距
                    // 应用段落样式
                    mutableAttributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: fullRange)
                    mutableAttributedString.addAttribute(.foregroundColor, value: UIColor.white, range: fullRange)
                    mutableAttributedString.addAttribute(.font, value: 14.font_regular!, range: fullRange)
                    contentLabel.attributedText = mutableAttributedString // 设置富文本
//                    let maxSize = CGSize(width: .screenWidth-24.0.Scale, height: CGFloat.greatestFiniteMagnitude)
//                    let textBounds = attributedString.boundingRect(
//                        with: maxSize,
//                        options: [.usesLineFragmentOrigin, .usesFontLeading],
//                        context: nil
//                    )
//                    contentLabel.heightConstraint?.constant = textBounds.height
                }
            }
            self.scores = md.scrapys?.scores
            self.actives = md.actives
            self.tableView.heightConstraint?.constant = Double(md.actives.count) * 36.0.Scale
            self.tableView.reloadData()
        }
    }
    
    var scores: [ClubGameDetailScrapysItemModel]?{
        didSet{
            guard let models = scores else { return }
            let numberOfRows = Int(ceil(Double(models.count) / Double(2)))
            collectionView.heightConstraint?.constant = Double(numberOfRows) * 30.0.Scale
            collectionView.reloadData()
        }
    }
    
    var actives:[ClubGameCommunityNewsModel]?
    var toIntroVCBlock: (() -> Void)?
    var jumpToDetail:((_:ClubGameCommunityNewsModel)->())?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            contentLabel
            collectionView
            tableView
        }

        contentLabel.leading(12.0.Scale).trailing(12.0.Scale).top(0)
        collectionView.leading(12.0.Scale).trailing(12.0.Scale).height(30.0.Scale)
        collectionView.Top == contentLabel.Bottom + 8.0.Scale
        tableView.leading(12.0.Scale).trailing(12.0.Scale).height(36.0.Scale).bottom(12.0.Scale)
        tableView.Top == collectionView.Bottom + 4.0.Scale
        
        let w = (CGFloat.screenWidth - 24.0.Scale)/2
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: w, height: 30.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubGameDetailGamePointItemCell.self, forCellWithReuseIdentifier: ClubGameDetailGamePointItemCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        
        let contentTap = UITapGestureRecognizer(target: self, action: #selector(clickContentTap))
        contentLabel.isUserInteractionEnabled = true
        contentLabel.addGestureRecognizer(contentTap)
    }
    
    @objc private func clickContentTap(){
        toIntroVCBlock?()
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return scores?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubGameDetailGamePointItemCell.description(), for: indexPath) as? ClubGameDetailGamePointItemCell else { return UICollectionViewCell() }
        cell.model = scores?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return actives?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailActiveCell", for: indexPath) as! ClubGameDetailActiveCell
        cell.model = actives?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let md = actives?[indexPath.row] else { return }
        jumpToDetail?(md)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

class ClubGameDetailGamePointItemCell: UICollectionViewCell {
    
    private let titleLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.6)).font(12.font_medium).end()

    var model: ClubGameDetailScrapysItemModel?{
        didSet{
            guard let md = model else { return }
            titleLabel.text = md.source_text + "：" + md.score
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            titleLabel
        }
              
        
        titleLabel.leading(0).trailing(5).centerVertically()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class ClubGameDetailActiveCell: UITableViewCell {
    
    private let tagLabel = c_make_ex(UILabel.self)
        .border("#FF7500".toColor.alpha(0.5), width: 1)
        .color("#FF7500").corner(2).font(9.font_semiBold)
        .alignment(.center).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color(.white).font(14.font_medium).end()
    private let rightImageView = c_make_ex(UIImageView.self)
        .mode(.scaleToFill).image("Square_detail_right").end()
    
    var model: ClubGameCommunityNewsModel?{
        didSet{
            guard let md = model else { return }
            tagLabel.text = md.type
            contentLabel.text = model?.title
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            tagLabel
            contentLabel
            rightImageView
        }

        tagLabel.leading(16.0.Scale).width(26.0.Scale).height(14.0.Scale).centerVertically()
        rightImageView.trailing(16.0.Scale).size(14).centerVertically()
        contentLabel.leading(48.0.Scale).trailing(45.0.Scale).centerVertically()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }


}


//MARK: =================WelfareCell=================
class ClubGameDetailWelfareCell: UITableViewCell {

    private let contentImageV = c_make_ex(UIView.self)
        .corner(12.0.Scale).bgColor(.black.alpha(0.2)).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color(.white).font(14.font_regular)
        .text("暂无福利活动，敬请期待！").alignment(.center).end()
    private let welfareLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.9)).font(14.font_regular).line(0).end()
    
    var model: ClubGameDetailInfoModel? {
        didSet{
            guard let md = model else { return }
            
            if md.fuli.count > 0 {
                
                contentImageV.isHidden = true
                contentLabel.isHidden = true
                welfareLabel.isHidden = false
                
                welfareLabel.text = md.fuli
                let height = md.fuli.calculateTextHeight(font: 14.font_regular!, width: .screenWidth - 24.0.Scale) + 16.0.Scale
                welfareLabel.heightConstraint?.constant = height
            }else{
                
                contentImageV.isHidden = false
                contentLabel.isHidden = false
                welfareLabel.isHidden = true
                
                welfareLabel.heightConstraint?.constant = 68.0.Scale
            }
        }
        
        
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            contentImageV.subviews{
                contentLabel
            }
            welfareLabel
        }
        
        contentImageV.leading(12.0.Scale).trailing(12.0.Scale).top(8.0.Scale).bottom(8.0.Scale)
        contentLabel.centerHorizontally().centerVertically()
        welfareLabel.leading(12.0.Scale).trailing(12.0.Scale).top(8.0.Scale).bottom(8.0.Scale).height(68.0.Scale)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

//MARK: =================
class ClubGameDetailCommitCell: UITableViewCell {
    
    private let bgView = c_make_ex(UIView.self)
        .bgColor(.white.alpha(0.9)).corner(12.0.Scale).end()
    private let moreButton = c_make_ex(UIButton.self)
        .image("Mine_Commit_more").end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(20.0.Scale).mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(12.font_semiBold).end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).end()
    private let jingImageView = c_make_ex(UIImageView.self)
        .image("GameDetail_jing").mode(.scaleAspectFill).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color("#47494D").font(15.font_medium)
        .line(3).end()
    private let contentImageView = c_make_ex(UIImageView.self)
        .corner(8.0.Scale).mode(.scaleAspectFill).end()
    private let likeButton = UIIconButton(style: .top(itemSpace: 0))
    private let commitButton = UIIconButton(style: .top(itemSpace: 0))
    private let sonCommitView = c_make_ex(UIView.self)
        .bgColor("#EDEEF0").corner(8).end()
    private let sonCommitLabel = c_make_ex(UILabel.self)
        .color("#4B4C4D").font(13.font_medium)
        .line(2).end()
    
    var starView = CosmosView()
   

    var didSelectImage:((_:Int,_:[String])->())?
    var clickLikeBlock: ((_ id: String) -> Void)?
    /// 更多
    var showMoreView: ((_ model: ClubGameDetailCommentListModel) -> Void)?
    /// 用户主页
    var userInfoVC: ((_ uid: String) -> Void)?
    
    var isWhite = false {
        didSet{
            if isWhite {
                backgroundColor = UIColor.white
                bgView.backgroundColor = "#F7F8FA".toColor
                moreButton.isHidden = false
            }else{
                backgroundColor = UIColor.clear
                bgView.backgroundColor = .white.alpha(0.9)
                moreButton.isHidden = true
            }
        }
    }
    
    var model: ClubGameDetailCommentListModel? {
        didSet{
            guard let md = model else { return }
            
            iconImageView.loadImage(url: md.touxiang)
            contentLabel.text = md.content
            nameLabel.text = md.user_name
            timeLabel.text = md.timetran
            starView.rating = md.point/2
            likeButton.isSelected = md.is_zan
            jingImageView.isHidden = !(md.jiajing == "1")
            if md.zan != "0" {
                likeButton.setTitle(md.zan, for: .normal)
            }else{
                likeButton.setTitle("点赞", for: .normal)
            }
            if md.num != "0" {
                commitButton.setTitle(md.num, for: .normal)
            }else{
                commitButton.setTitle("评论", for: .normal)
            }
            if md.images.count > 0 {
                contentImageView.isHidden = false
                let imgUrl = md.images[0]
                let imageUrl = URL(string: imgUrl)!
                self.checkImageOrientation(from: imageUrl) { orientation,image in
                    DispatchQueue.main.async {
                        self.contentImageView.image = image
                        if orientation == "横图" {
                            self.contentImageView.heightConstraint?.constant = 107.0.Scale
                            self.contentImageView.widthConstraint?.constant = 190.0.Scale
                        }else{
                            self.contentImageView.heightConstraint?.constant = 107.0.Scale
                            self.contentImageView.widthConstraint?.constant = 107.0.Scale
                        }
                    }
                }
                sonCommitView.topConstraint?.constant = 115.0.Scale
            }else{
                contentImageView.isHidden = true
                contentImageView.heightConstraint?.constant = 0
                contentImageView.widthConstraint?.constant = 0
                sonCommitView.topConstraint?.constant = 0
            }
            
            if md.son_list.count > 0 {
                sonCommitView.isHidden = false
                let son_m = md.son_list[md.son_list.count - 1]
                let preStr = son_m.user_name + "："
                sonCommitLabel.attributedText = createAttributedText(prefixText: preStr, prefixColor: "#323233".toColor, prefixFont: 13.font_semiBold!, mainText: son_m.content, mainColor: "#4B4C4D".toColor, mainFont: 13.font_medium!)
                let commitStr = preStr + son_m.content
                var commitLabH = commitStr.calculateTextHeight(font: 13.font_medium!, width: CGFloat.screenWidth - 72.0.Scale)
                if commitLabH > 20 {
                    commitLabH = 37.0
                }else{
                    commitLabH = 19.0
                }
                sonCommitView.heightConstraint?.constant = commitLabH + 16.0.Scale
                commitButton.topConstraint?.constant = commitLabH + 22.0.Scale
            }else{
                sonCommitView.isHidden = true
                sonCommitView.heightConstraint?.constant = 0
                commitButton.topConstraint?.constant = 0
            }
        }
        
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.white
        
        contentView.subviews{
            bgView.subviews{
                moreButton
                iconImageView
                nameLabel
                timeLabel
                jingImageView
                contentLabel
                contentImageView
                sonCommitView.subviews{
                    sonCommitLabel
                }
                commitButton
                likeButton
                starView
            }
        }
        
        bgView.leading(12.0.Scale).trailing(12.0.Scale).top(0).bottom(12.0.Scale)
        moreButton.trailing(8.0.Scale).top(20.0.Scale).size(32.0.Scale)
        iconImageView.leading(12.0.Scale).top(16.0.Scale).size(40.0.Scale)
        nameLabel.leading(64.0.Scale).top(22.0.Scale).trailing(15.0.Scale)
        timeLabel.leading(64.0.Scale).top(40.0.Scale).trailing(15.0.Scale)
        starView.leading(12.0.Scale).top(68.0.Scale).width(92.0.Scale).height(12.0.Scale)
        jingImageView.trailing(0).top(50.0.Scale).size(82.0.Scale)
        contentLabel.leading(12.0.Scale).trailing(12.0.Scale)
        contentLabel.Top == starView.Bottom + 5.0.Scale
        contentImageView.leading(12.0.Scale).width(107.0.Scale).height(107.0.Scale)
        contentImageView.Top == contentLabel.Bottom + 12.0.Scale
        sonCommitView.leading(12.0.Scale).trailing(12.0.Scale)
        sonCommitView.Top == contentImageView.Top + 115.0.Scale
        sonCommitLabel.leading(8.0.Scale).trailing(16.0.Scale).top(8.0.Scale).bottom(8.0.Scale)
        commitButton.leading(74.0.Scale).height(40.0.Scale).bottom(10.0.Scale)
        commitButton.Top == sonCommitView.Top + 30.0.Scale
        likeButton.trailing(74.0.Scale).height(40.0.Scale)
        likeButton.CenterY == commitButton.CenterY
        
        
        starView.rating = 0
        starView.settings.starSize = 12.0.Scale
        starView.settings.starMargin = 4
        starView.settings.fillMode = .half
        starView.settings.emptyImage = "Common_emptyStar".toImage
        starView.settings.filledImage = "Common_fillStar".toImage
        starView.isUserInteractionEnabled = false
        
        jingImageView.isHidden = true
        contentLabel.lineBreakMode = .byTruncatingTail
//        lookButton.isUserInteractionEnabled = false
        commitButton.isUserInteractionEnabled = false
        likeButton.addTarget(self, action: #selector(clickLikeButton), for: .touchUpInside)
        let imgTap = UITapGestureRecognizer(target: self, action: #selector(contentImageViewTap))
        contentImageView.isUserInteractionEnabled = true
        contentImageView.addGestureRecognizer(imgTap)
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
        
        iconImageView.isUserInteractionEnabled = true
        let iconTap = UITapGestureRecognizer(target: self, action: #selector(clickUserIcon))
        iconImageView.addGestureRecognizer(iconTap)
        
        likeButton.style { v in
            v.iconSize = CGSize(width: 28, height: 28)
            v.setImage("GameDetail_like".toImage, for: .normal)
            v.setImage("GameDetail_liked".toImage, for: .selected)
            v.setTitleColor("#7D7E80".toColor, for: .normal)
            v.setTitleColor(ClubGlobalTool.shared.likeColor, for: .selected)
            v.titleLabel?.font = 10.font_medium
        }
        commitButton.style { v in
            v.iconSize = CGSize(width: 28, height: 28)
            v.setImage("GameDetail_comment".toImage, for: .normal)
            v.setTitleColor("#7D7E80".toColor, for: .normal)
            v.titleLabel?.font = 10.font_medium
            v.setTitle("点赞", for: .normal)
        }
    }
    
    @objc private func clickUserIcon(){
        userInfoVC?(model?.uid_des ?? "")
    }
    
    @objc private func contentImageViewTap(){
        didSelectImage?(0,model?.images ?? [])
    }
    
    @objc private func clickLikeButton(){
        clickLikeBlock?(model?.id ?? "")
    }
    
    @objc private func clickMoreButton(){
        guard let md = model else { return }
        showMoreView?(md)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func checkImageOrientation(from url: URL, completion: @escaping (String,UIImage) -> Void) {
        // 异步加载图片
        URLSession.shared.dataTask(with: url) { data, response, error in
            // 检查是否成功获取数据
            guard let data = data, error == nil, let image = UIImage(data: data) else {
                completion("加载图片失败",UIImage())
                return
            }
            
            // 获取图片尺寸
            let width = image.size.width
            let height = image.size.height
            
            // 判断横竖图
            if width > height {
                completion("横图",image)
            } else if height > width {
                completion("竖图",image)
            } else {
                completion("正方形",image)
            }
            
        }.resume()
    }
    
    // 创建一个带有不同颜色和大小的富文本
    func createAttributedText(prefixText: String, prefixColor: UIColor, prefixFont: UIFont, mainText: String, mainColor: UIColor, mainFont: UIFont) -> NSAttributedString {
        
        // 创建前缀部分的富文本
        let prefixAttributedString = NSMutableAttributedString(string: prefixText, attributes: [
            .foregroundColor: prefixColor,
            .font: prefixFont
        ])
        
        // 创建主文本部分的富文本
        let mainAttributedString = NSAttributedString(string: mainText, attributes: [
            .foregroundColor: mainColor,
            .font: mainFont
        ])
        
        // 将前缀和主文本拼接
        prefixAttributedString.append(mainAttributedString)
        
        return prefixAttributedString
    }
}


//MARK: =================
class ClubGameDetailBottomView: UIView {

    private let saysButton = c_make_ex(UIButton.self)
        .corner(17.0.Scale).bgColor(.black.alpha(0.05))
        .color("#7B7D80").font(13.font_medium)
        .text("  写点什么...").end()
    private let commitButton = UIIconButton(style: .top(itemSpace: 2))

    var clickCommitBlock: (() -> Void)?
    
    var number = 0 {
        didSet{
            if number == 0 {
                commitButton.setTitle("评论", for: .normal)
            }else{
                commitButton.setTitle("\(number)", for: .normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .white
        
        subviews{
            saysButton
            commitButton
        }
        
        commitButton.style { v in
            v.iconSize = CGSize(width: 24.0.Scale, height: 24.0.Scale)
            v.setImage("Home_detail_commit".toImage, for: .normal)
//            v.setImage("Detail_commit_sel".toImage, for: .selected)
            v.setTitle("评论", for: .normal)
            v.setTitleColor("#2E3033".toColor, for: .normal)
            v.setTitleColor("#FF7600".toColor, for: .selected)
            v.titleLabel?.font = 10.font_medium
            v.addTarget(self, action: #selector(clickCommitButton), for: .touchUpInside)
        }
        
        saysButton.contentHorizontalAlignment = .left
        commitButton.top(4.0.Scale).size(44.0.Scale).trailing(12.0.Scale)
        saysButton.leading(12.0.Scale).height(34.0.Scale).trailing(72.0.Scale).top(9.0.Scale)
        
        saysButton.addTarget(self, action: #selector(clickCommitButton), for: .touchUpInside)
    }
    
    @objc private func clickCommitButton(){
        clickCommitBlock?()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class ClubGameDetailEmptyCommitCell: UITableViewCell {
    
    private let bgView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12, corners: [.layerMinXMinYCorner,.layerMaxXMinYCorner]).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(24.0.Scale).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#FF7700").font(12.font_semiBold).alignment(.center)
        .text("发布游戏首评").end()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#7D7E80").font(12.font_medium).alignment(.center)
        .text("- 轻触说说你的想法 -").end()
    private var starView = CosmosView()
    private let starButton = c_make_ex(UIButton.self).end()
    private let lineView = c_make_ex(UIView.self)
        .bgColor("#E1E2E5").end()
    
    var starBlock: (() -> Void)?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            bgView.subviews{
                iconImageView
                titleLabel
                subLabel
                starView
                starButton
                lineView
            }
        }
        
        bgView.leading(0).trailing(0).top(0).height(190.0.Scale).bottom(0)
        iconImageView.top(24.0.Scale).size(48.0.Scale).centerHorizontally()
        titleLabel.centerHorizontally()
        titleLabel.Top == iconImageView.Bottom + 5.0.Scale
        subLabel.centerHorizontally()
        subLabel.Top == titleLabel.Bottom + 5.0.Scale
        starView.width(180.0.Scale).height(32.0.Scale).centerHorizontally()
        starView.Top == subLabel.Bottom + 15.0.Scale
        starButton.width(180.0.Scale).height(32.0.Scale).centerHorizontally()
        starButton.Top == subLabel.Bottom + 15.0.Scale
        lineView.leading(0).trailing(0).bottom(0).height(1)
        
        starView.rating = 0
        starView.settings.starSize = 32.0.Scale
        starView.settings.starMargin = 5.0.Scale
        starView.settings.emptyImage = "GameDetail_commitStar".toImage
        starView.isUserInteractionEnabled = false
        
        if ClubUser.face.count > 0 {
            iconImageView.loadImage(url: ClubUser.face)
        }else{
            iconImageView.image = "Common_defaultIcon".toImage
        }
        
        starButton.addTarget(self, action: #selector(clickStarButton), for: .touchUpInside)
    }

    @objc private func clickStarButton(){
        starBlock?()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }


}
